//
//  GYUserSetViewController.m
//  GoodLuck
//
//  Created by apple on 2018/3/2.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYUserSetViewController.h"
#import "GYSetCell.h"
#import "GYUser.h"
#import "GYUserFeedbackViewController.h"
#import "GYModifyPasswordViewController.h"
#import "GYNetWorkTools.h"
#import "GYBasePopoverViewController.h"
#import "PopoverAnimation.h"
#import "GYSearchViewController.h"
#import "GYSystemMessageViewController.h"
#import "GYAboutUsViewController.h"
#import "GYNetWorkTools.h"
#import "GYVerificationViewController.h"

static NSString *cellID = @"cellID";
static NSString *clearCachesIdentifier = @"clearCachesIdentifier";
static NSString *newVersionIdentifier = @"newVersionIdentifier";

@interface GYUserSetViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *userSetTableView;

/** title */
@property (nonatomic, strong) NSArray *titles;

/** 提示内容 */
@property (nonatomic, strong) NSArray *contens;

/** 动画代理 */
@property (nonatomic, strong) PopoverAnimation *animationDelegate;

/** 第二分区标题 */
@property (nonatomic, strong) NSArray *secondTitles;

/** 标记当前是否设置密码 */
@property (nonatomic, assign) NSInteger payPassWordState;
@end

@implementation GYUserSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"设置";
    self.userSetTableView.backgroundColor = RGBColor(245, 245, 245);
    self.userSetTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.userSetTableView.sectionFooterHeight = 15;
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"more_b" tagret:self action:@selector(moreBtuClick) button:nil];

    //检查支付密码是否设置
    [self judgePayPassworkIsSet];
}

- (void)judgePayPassworkIsSet {
    [GYNetWorkTools requestVerPayPwd:^(NSDictionary *obj) {
        //NSLog(@"obj=========%@",obj);
        int code = [[obj objectForKey:@"code"] intValue];
        if (code == 200) {
            self.payPassWordState = [[obj objectForKey:@"datas"] integerValue];
            [self.userSetTableView reloadData];
        }
    } error:^(NSError *error) {
        NSLog(@"error===========%@",error);
    }];
}

- (void)moreBtuClick {
    GYBasePopoverViewController *basePopoverVC = [[GYBasePopoverViewController alloc] initWithNibName:@"GYBasePopoverViewController" bundle:nil];
    __weak typeof(self) weakSelf = self;
    basePopoverVC.popoverViewSelectIndexCallBack = ^(NSInteger index) {
        switch (index) {
            case 0:
            {
                weakSelf.tabBarController.selectedIndex = 0;
                [weakSelf.tabBarController.tabBar setHidden:NO];
            }
                break;
                
            case 1:
            {
                GYSearchViewController *searchVC = [[GYSearchViewController alloc] init];
                [self.navigationController pushViewController:searchVC animated:YES];
            }
                break;
                
            case 2:
            {
                GYSystemMessageViewController *systemMessageVC = [[GYSystemMessageViewController alloc] initWithNibName:@"GYSystemMessageViewController" bundle:nil];
                systemMessageVC.hidesBottomBarWhenPushed = YES;
                [weakSelf.navigationController pushViewController:systemMessageVC animated:YES];

            }
                break;
                
            default:
                break;
        }
    };
    basePopoverVC.titles = @[@"首页",@"搜索",@"消息"];
    basePopoverVC.images = @[@"home_w",@"search_w",@"message_w"];
    
    self.animationDelegate = [[PopoverAnimation alloc] init];
    self.animationDelegate.popoverFrame = CGRectMake(ScreenWidth-widthScale(130, iphone6_W)-5, 50, widthScale(130, iphone6_W), basePopoverVC.titles.count*50);
    basePopoverVC.transitioningDelegate = (id)weakSelf.animationDelegate;
    
    basePopoverVC.modalPresentationStyle = UIModalPresentationCustom;
    [self presentViewController:basePopoverVC animated:YES completion:nil];

}


#pragma mark -- UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return section == 2 ? self.secondTitles.count : 1;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:clearCachesIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:clearCachesIdentifier];
            }
            cell.textLabel.text = self.secondTitles[indexPath.row];
            cell.textLabel.font = [UIFont systemFontOfSize:16];
            cell.backgroundColor = [UIColor whiteColor];
            
            //计算缓存
            NSArray *source = [[NSArray alloc] initWithContentsOfFile:[NSString CachesDir:@"homeData.plist"]];
            if (source != nil) {
                NSData *data = [NSJSONSerialization dataWithJSONObject:source options:NSJSONWritingPrettyPrinted error:nil];
                float cachesM = (CGFloat)data.length/1024;
                if (cachesM >=1024) {
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"%0.1fMB",cachesM/1024];
                }else if (cachesM >0 && cachesM < 1024) {
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"%0.1fKB",cachesM];
                }else {
                    cell.detailTextLabel.text = @"";
                }
            }else {
                cell.detailTextLabel.text = @"";
            }
            
            return cell;
        }else {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            }
            cell.textLabel.text = self.secondTitles[indexPath.row];
            cell.textLabel.font = [UIFont systemFontOfSize:16];
            cell.backgroundColor = [UIColor whiteColor];
            
            return cell;
        }
    }else {
        GYSetCell *cell = [GYSetCell cellWithTbaleView:tableView];
        cell.titleLable.text = self.titles[indexPath.section][indexPath.row];
        cell.contentLable.text = self.contens[indexPath.section][indexPath.row];
        if (indexPath.section == 0) {
            cell.setLable.hidden = NO;
            cell.setLable.text = self.payPassWordState == 1 ? @"已设置" : @"未设置";
        } else {
            cell.setLable.hidden = YES;
        }
        
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 2) {
        switch (indexPath.row) {
            case 0:
            {
                NSLog(@"清除缓存");
                UIAlertController *alertViewControlelr = [UIAlertController alertControllerWithTitle:@"是否清除缓存!" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
                UIAlertAction *sub = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    //清除缓存
                    NSString *cachesPath = [NSString CachesDir:@"homeData.plist"];
                    BOOL isSuccess = [[NSFileManager defaultManager] removeItemAtPath:cachesPath error:nil];
                    if (isSuccess) {
                        [EasyTextView showText:@"清除缓存成功!"];
                    }else {
                        [EasyTextView showText:@"清除缓存失败!"];
                    }
                    [tableView reloadData];
                }];
                
                [alertViewControlelr addAction:cancel];
                [alertViewControlelr addAction:sub];
                
                [self presentViewController:alertViewControlelr animated:YES completion:nil];
            }
                break;
                
            case 1:
            {
                NSLog(@"关于我们");
                GYAboutUsViewController *aboutController = [[GYAboutUsViewController alloc] initWithNibName:@"GYAboutUsViewController" bundle:nil];
                [self.navigationController pushViewController:aboutController animated:YES];
            }
                break;
        
            case 2:
            {
                UIAlertController *alertViewControlelr = [UIAlertController alertControllerWithTitle:@"确定退出登录吗?" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                UIAlertAction *sub = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    //退出登录
                    [GYNetWorkTools requestUserSignOut:^(NSDictionary *obj) {
                        //NSLog(@"obj ==== %@",obj);
                        int code = [[obj objectForKey:@"code"] intValue];
                        id datas = [obj objectForKey:@"datas"];
                        if (code == 200) {
                            [EasyTextView showSuccessText:@"安全退出成功!"];
                            //1.删除个人用户信息
                            [GYUser removeUserInfo];
                            
                            //更换界面
                            self.tabBarController.selectedIndex = 0;
                            
                            [self.navigationController popViewControllerAnimated:YES];
                        }else if (code == 400){
                            [EasyTextView showSuccessText:@"退出失败!"];
                            NSLog(@"安全退出 出现错误===%@",[datas objectForKey:@"error"]);
                        }
                    } error:^(NSError *error) {
                        [EasyTextView showSuccessText:@"退出失败!"];
                        NSLog(@"用户安全退出出错...");
                    }];
                }];
                
                [alertViewControlelr addAction:cancel];
                [alertViewControlelr addAction:sub];
                
                [self presentViewController:alertViewControlelr animated:YES completion:nil];
                
            }
                break;
                
            default:
                break;
        }
    }else if(indexPath.section == 1) {
        GYUserFeedbackViewController *feedBackVC = [[GYUserFeedbackViewController alloc] initWithNibName:@"GYUserFeedbackViewController" bundle:nil];
        [self.navigationController pushViewController:feedBackVC animated:YES];
    }else {
        NSLog(@"设置支付密码");
        GYVerificationViewController *verificationVC = [[GYVerificationViewController alloc] initWithNibName:@"GYVerificationViewController" bundle:nil];
        verificationVC.currentPhone = self.currentPhone;
        [self.navigationController pushViewController:verificationVC animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2) {
        return 44;
    }
    GYSetCell *cell = [GYSetCell cellWithTbaleView:tableView];

    return [cell getHeight];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 15)];
    view.backgroundColor = [UIColor clearColor];
    
    return view;
}





#pragma mark -- 懒加载

- (NSArray *)secondTitles {
    if (!_secondTitles) {
        _secondTitles = @[@"清楚缓存",@"关于我们",@"安全退出"];
    }
    
    return _secondTitles;
}

- (NSArray *)titles {
    if (!_titles) {
        _titles = @[@[@"支付密码"],@[@"用户反馈"]];
    }
    
    return _titles;
}

- (NSArray *)contens {
    if (!_contens) {
        _contens = @[@[@"建议您设备复杂的密码保护您的财产安全"],
                     @[@"您再使用中遇到的问题与建议可向我们反馈"]
                     ];
    }
    
    return _contens;
}
@end
